package treex

import "gitee.com/zhongguo168a/gocodes/datax"

type TreeListItem struct {
	/**
	 * 编号
	 */
	Id string
	/**
	 * 父编号
	 */
	Parent string

	/**
	 * 自定义数据
	 */
	Data interface{}
}

func NewByList(arr []*TreeListItem) *TreeRoot {
	nodes := datax.M{
		"/": nil,
	}
	var root *TreeRoot
	for _, val := range arr {
		node := &TreeNode{Id: val.Id}
		nodes[val.Id] = node
		node.Data = val.Data
	}
	root = NewTreeRoot()
	if nodes["/"] == nil {
		nodes["/"] = root
	} else {
		a := nodes["/"].(*TreeNode)
		root.TreeNode = *a
		nodes["/"] = root
	}
	for _, val := range arr {
		node := nodes[val.Id]
		iparent, hasParent := nodes[val.Parent]
		if hasParent {
			parent := iparent.(ITreeNode)
			parent.AddChild(node.(*TreeNode))
		}
	}
	return root
}
